const pool = require('../config/database');
const Jwt = require('../utils/jwt');

class TaskModel {
  /**
   * 获取全部任务
   * @param {*} ctx
   * @returns 
   */
  async getTaskList(ctx) {
    const current = Number(ctx.query.current);
    const pageSize = Number(ctx.query.pageSize);
    const status = Number(ctx.query.status); // 状态
    const offset = (current - 1) * pageSize;
    const unfinishStatus = 0;
    const sortField = ctx.query.sortField;
    const sortValue = ctx.query.sortValue;

    const authHeader = ctx.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];
    const decoded = Jwt.verifyToken(token, process.env.JWT_SECRET);

    const sql_role = `SELECT id, role FROM users WHERE id=${decoded.userId}`;
    const [[user]] = await await pool.query(sql_role);
    const ROLE_ADMIN_VALUE = 1;
    const notAdmit = (user && user.role & ROLE_ADMIN_VALUE) !== ROLE_ADMIN_VALUE;

    let sql_count = 'SELECT COUNT(id) AS value FROM task_list';
    let sql_list = `SELECT 
      t.id,
      t.title,
      t.datetime,
      t.author,
      t.status,
      t.author_id,
      u.fullname AS authorName `;
    let sql_unfinish = `SELECT COUNT(id) AS value FROM task_list WHERE status=${unfinishStatus}`

    let ORDER_BY_CONDITION = '';
    if (sortField && sortValue) {
      ORDER_BY_CONDITION = ` ORDER BY ${sortField} ${sortValue} `;
    }

    let WHERE_CONDITION = '';
    if (status !== -1) {
      WHERE_CONDITION = ` WHERE status=${status} `;
    }

    if (notAdmit) {
      if (WHERE_CONDITION) {
        WHERE_CONDITION += ` AND author_id=${user.id} `
      } else {
        WHERE_CONDITION = ` WHERE author_id=${user.id} `
      }
      sql_unfinish += ` AND author_id=${user.id}`;
    }

    if (status === -1) {
      sql_count += WHERE_CONDITION;
      sql_list += `
        FROM task_list t
        LEFT JOIN users u ON t.author_id = u.id
        ${WHERE_CONDITION}
        ${ORDER_BY_CONDITION}
        LIMIT ${pageSize} OFFSET ${offset}`;
    } else {
      sql_count += WHERE_CONDITION;
      sql_list += `
        FROM task_list t
        LEFT JOIN users u ON t.author_id = u.id
        ${WHERE_CONDITION}
        ${ORDER_BY_CONDITION}
        LIMIT ${pageSize} OFFSET ${offset}`;
    }

    // const testSql = `
    //   SELECT t.*, u.fullname AS author_name
    //   FROM task_list t 
    //   LEFT JOIN users u ON t.author_id = u.id
    // `;
    // const testRes = await pool.query(testSql);
    // console.log('testRes', testRes);

    const [[unfinishCount]] = await pool.query(sql_unfinish);
    const [[count]] = await pool.query(sql_count);
    const [rows] = await pool.query(sql_list);

    const data = rows.map(row => {
      const target = {
        ...row, authorId: row.author_id
      }

      delete target.author_id;
      return target;
    });

    return {
      data,
      current,
      pageSize,
      total: count.value,
      unfinishCount: unfinishCount.value
    }
  }

  /**
   * 添加
   * @param {*} task 
   * @returns 
   */
  async addTask(task) {
    const { title, datetime, author, authorId, status } = task;
    const sql = `
      INSERT INTO task_list 
      (title, datetime, author, author_id, status) 
      VALUES (?, ?, ?, ?, ?)
    `;
    const [result] = await pool.query(
      sql,
      [title, datetime, author, authorId, status]
    );

    return result.insertId;
  }

  /**
   * 更新
   * @param {*} id 
   * @param {*} task 
   * @returns 
   */
  async updateTask(id, task) {
    const { title, datetime, author, authorId, status } = task;
    const sql = `
      UPDATE task_list 
      SET title=?, datetime=?, author=?, author_id=?, status=?
      WHERE id=?
    `;
    const [result] = await pool.query(sql, [
      title, datetime, author, authorId, status, id
    ]);

    return result.affectedRows;
  }

  /**
   * 删除
   * @param {*} id 
   * @returns 
   */
  async deleteTask(id) {
    const sql = 'DELETE FROM task_list WHERE id=?';
    const [result] = await pool.query(sql, [id]);

    return result.affectedRows;
  }
}

module.exports = new TaskModel();